package com.gitee.wsl.collections.iterator

import com.gitee.wsl.base.Objects
import com.gitee.wsl.func.comparable.Equator


class SortedUniqueIterator<E>(
    private val iterator: Iterator<E>,
    private val equalsChecker: Equator<E>
) : Iterator<E> {
    private var next: E? = null

    init {
        // 初始化时预取第一个元素作为next
        next = if (iterator.hasNext()) {
            iterator.next()
        } else {
            null
        }
    }

//    constructor(iterator: Iterator<E>) : this(
//        iterator,
//        IEqualsChecker { obj: Objects, a: T, b: T -> obj!!.equals(a, b) })

    public override fun hasNext(): Boolean {
        return next != null
    }

    public override fun next(): E {
        if (!hasNext()) {
            throw NoSuchElementException()
        }
        val current = next
        next = null
        // 寻找下一个不等于current的元素
        while (iterator.hasNext()) {
            val candidate = iterator.next()
            if (!equalsChecker.equate(candidate, current!!)) {
                next = candidate
                break
            }
        }
        return current!!
    }
}